package main

import "fmt"

// bitmap存储0/1数据
type Bitmap struct {
	//存放记录数据
	data []uint8
}

func set(bitmap *Bitmap, pos int) {
	if pos < 0 {
		return
	}
	requiredBits := pos - (len(bitmap.data)<<3 - 1)
	//如果大于0 则需要扩容
	if requiredBits > 0 {
		expandBitmap(bitmap, requiredBits)
	}
	elementIndex := pos >> 3
	bitmap.data[elementIndex] = bitmap.data[elementIndex] | 1<<(pos%8)
}

func checkPos(bitmap *Bitmap, pos int) {
	if pos-(len(bitmap.data)<<3) > 1 {
		fmt.Println(pos, "数据不存在")
	}
	elementIndex := pos >> 3
	setting := (bitmap.data[elementIndex] & (1 << (pos % 8))) > 0
	fmt.Println(pos, "是否存在", setting)
}

func expandBitmap(bitmap *Bitmap, space int) {
	element2Expand := (space + 7) >> 3
	newData := make([]uint8, element2Expand+len(bitmap.data))
	copy(newData, bitmap.data)
	bitmap.data = newData
}

func main() {
	b := new(Bitmap)
	set(b, 4)
	checkPos(b, 4)
	checkPos(b, 5)
}
